<script lang="ts" setup>
import { reactive, ref, watch } from "vue"
import { batchUpateStatusApi, getUserDataApi } from "@/api/user-manage"
import { type UserData } from "@/api/user-manage/types/user"
import { type FormInstance, ElMessage, ElMessageBox, TableInstance } from "element-plus"
import { Search, Refresh, Download, RefreshRight, Remove, Open } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"

defineOptions({
  // 命名当前组件
  name: "UserManage"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()



const handleDisable = (row: UserData) => {
  ElMessageBox.confirm(`正在禁用用户：${row.nickname}，确认禁用？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    batchUpateStatusApi([row.id], 0).then(() => {
      ElMessage.success("禁用成功")
      getUserData()
    })
  })
}

const handleEnable = (row: UserData) => {
  ElMessageBox.confirm(`正在启用用户：${row.nickname}，确认启用？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    batchUpateStatusApi([row.id], 1).then(() => {
      ElMessage.success("启用成功")
      getUserData()
    })
  })
}


//#region 查
const userData = ref<UserData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  nickname: "",
  phone: ""
})
const getUserData = () => {
  loading.value = true
  getUserDataApi({
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    nickname: searchData.nickname || undefined,
    phone: searchData.phone || undefined
  })
    .then(({ data }) => {
      paginationData.total = data.total
      userData.value = data.list
    })
    .catch(() => {
      userData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getUserData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

const userTableRef = ref<TableInstance>()

const batchDisable = async () => {
  const selection = userTableRef.value?.getSelectionRows()
  if (selection.length === 0) {
    ElMessage.warning('请选择需要禁用的用户')
    return
  }
  const ids = selection.map((item: UserData) => item.id)
  try {
    await batchUpateStatusApi(ids, 0)
    ElMessage.success('批量禁用成功')
    getUserData()
  } catch (error) {
    ElMessage.error('批量禁用失败')
  }
}

const batchEnable = async () => {
  const selection = userTableRef.value?.getSelectionRows()
  if (selection.length === 0) {
    ElMessage.warning('请选择需要启用的用户')
    return
  }
  const ids = selection.map((item: UserData) => item.id)
  try {
    await batchUpateStatusApi(ids, 1)
    ElMessage.success('批量启用成功')
    getUserData()
  } catch (error) {
    ElMessage.error('批量启用失败')
  }
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getUserData, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="nickname" label="用户昵称">
          <el-input v-model="searchData.nickname" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="searchData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <el-button type="success" :icon="Open" @click="batchEnable">批量启用</el-button>
          <el-button type="danger" :icon="Remove" @click="batchDisable">批量禁用</el-button>
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getUserData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table ref="userTableRef" :data="userData">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="nickname" label="用户昵称" align="center" />
          <el-table-column prop="avatar" label="头像" align="center">
            <template #default="scope">
              <el-image :src="scope.row.avatar" draggable="false">
                <template #placeholder>
                  <el-icon>
                    <Picture />
                  </el-icon>
                </template>
                <template #error>
                  <el-icon>
                    <Loading />
                  </el-icon>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" align="center" />
          <el-table-column prop="openid" label="OpenID" align="center" width="200" />
          <el-table-column prop="points" label="积分" align="center" />
          <el-table-column prop="status" label="状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status==1" type="success" effect="plain" disable-transitions>正常</el-tag>
              <el-tag v-else type="danger" effect="plain" disable-transitions>禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" />
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template #default="scope">
              <el-button v-if="scope.row.status==1" type="danger" text bg size="small" @click="handleDisable(scope.row)">禁用</el-button>
              <el-button v-else type="success" text bg size="small" @click="handleEnable(scope.row)">启用</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
